package com.opennews.openplatform.controller;

import com.opennews.openplatform.myspringbootcore.common.constant.HttpHeader;
import com.opennews.openplatform.myspringbootcore.common.constant.ServerCode;
import com.opennews.openplatform.myspringbootcore.common.constant.ServerError;
import com.opennews.openplatform.myspringbootcore.security.AuthRequestValidator;
import com.opennews.openplatform.myspringbootmvccore.helper.HttpResponseHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@RequiredArgsConstructor
@Component
public class AuthInterceptor implements HandlerInterceptor {
    protected final AuthRequestValidator authRequestValidator;
    protected final HttpResponseHelper httpResponseHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println(request.getRequestURI());

        boolean granted = authRequestValidator.checkAccessPermission(request.getMethod(), request.getRequestURI().trim(), request.getContextPath().trim(), request.getHeader(HttpHeader.HTTP_HEADER_AUTHORIZATION));

        if (!granted) {
            httpResponseHelper.sendErrorResponse(HttpStatus.UNAUTHORIZED.value(), ServerCode.UNAUTHORIZED, ServerError.ERROR_USER_ACCOUNT_NOT_AUTHORIZED, request.getRequestURI().trim());
        }

        return granted;
    }
}